package com.hty.PowerChat;

import java.io.File;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	//static String DATABASE_NAME = LoginActivity.path + File.separator + "HTYChat.db";
    static String DATABASE_NAME = "HTYChat.db";
	static int VERSION = 2;
	private SQLiteDatabase db;
	private static DBHelper mInstance = null;

	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, VERSION);
	}

	public static synchronized DBHelper getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new DBHelper(context);
		}
		return mInstance;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        switch (newVersion) {
            case 2:
                db.execSQL("DROP TABLE IF EXISTS chat");
                break;
        }
    }

	public void insert(String table, ContentValues values) {
		db = getWritableDatabase();
        db.execSQL("CREATE TABLE IF NOT EXISTS " + table + "(_id INTEGER PRIMARY KEY, message TEXT, mfrom TEXT, mto TEXT, time TEXT)");
		db.insert(table, null, values);
		db.close();
	}

    Cursor query(String table, String cid, String uid) {
        db = getWritableDatabase();
        db.execSQL("CREATE TABLE IF NOT EXISTS " + table + "(_id INTEGER PRIMARY KEY, message TEXT, mfrom TEXT, mto TEXT)");
        Cursor c = null;
        if(uid.equals("")){
            c = db.query(table, null, "mfrom='" + cid + "' or mto='" + cid + "'", null, null, null, "_id asc");
        }else {
            c = db.query(table, null, "mfrom='" + cid + "' and mto='" + uid + "' or mfrom='" + uid + "' and mto='" + cid + "'", null, null, null, "_id asc");  //先运算and，再运算or
        }
        return c;
    }

	int del(String table, int id) {
		if (db == null)
			db = getWritableDatabase();
		int rows = db.delete(table, "_id=?", new String[] { String.valueOf(id) });
		return rows;
	}

	@Override
	public void close() {
		if (db != null)
			db.close();
	}

}